package cn.turboinfo.fuyang.api.provider.common.component.order.listener

import cn.turboinfo.fuyang.api.entity.common.event.WrapperApplicationEvent
import cn.turboinfo.fuyang.api.entity.common.event.order.NewServiceOrderEvent
import cn.turboinfo.fuyang.api.provider.common.repository.database.order.ServiceOrderPO
import nxcloud.foundation.core.data.support.listener.EntityLifecycleListener
import org.springframework.context.ApplicationContext
import org.springframework.stereotype.Component
import org.springframework.transaction.support.TransactionSynchronization
import org.springframework.transaction.support.TransactionSynchronizationManager

@Component
class ServiceOrderPublishEventListener(
    private val applicationContext: ApplicationContext,
) : EntityLifecycleListener {

    override fun onPostPersist(entity: Any) {
        (entity as ServiceOrderPO)
            .let {
                TransactionSynchronizationManager.registerSynchronization(object : TransactionSynchronization {
                    override fun afterCommit() {
                        applicationContext.publishEvent(
                            WrapperApplicationEvent(
                                NewServiceOrderEvent.builder()
                                    .serviceOrderId(entity.id)
                                    .build()
                            )
                        )
                    }
                })
            }
    }

}